import '../request/base_request.dart';
import 'dio_adapter.dart';
import 'hi_error.dart';
import 'hi_net_adapter.dart';
import 'mock_adapter.dart';
import 'hi_interceptor.dart';

class HiNet {
    HiNet._();

    HiErrorInterceptor _hiErrorInterceptor;
    static HiNet _instance;

    static HiNet getInstance(){
        if(_instance == null){
            _instance = HiNet._();
        }

        return _instance;
    }

    Future fire(BaseRequest request) async {
        HiNetResponse response;
        var error;
        try {
            response = await send(request);
        } on HiNetError catch (e) {
            error = e;
            response = e.data;
            printLog(e.message);
        } catch(e) {
            error = e;
            printLog(e);
        }

        if (response == null){
            printLog(error);
        }

        var result = response.data;
        var status = response.statusCode;
        printLog(result);

        switch (status) {
            case 200:
                return result;
                break;
            case 401:
                throw NeedLogin();
                break;
            case 403:
                throw NeedAuth(result.toString(), data: result);
                break;
            default:
                throw HiNetError(status, result.toString(), data: result);
                break;
        }
    }

    void setErrorInterceptor(HiErrorInterceptor interceptor) {
        this._hiErrorInterceptor = interceptor;
    }

    Future<dynamic> send<T>(BaseRequest request) async {
        HiNetAdapter adapter = DioAdapter();

        return adapter.send(request);
    }

    void printLog(log) {
        print('hi_net:' + log.toString());
    }
}